package com.jh.paymentchannel.service;

import cn.jh.common.tools.Tools;
import cn.jh.common.utils.CommonConstants;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.pojo.ChannelDetail;
import com.jh.paymentchannel.pojo.TopupPayChannelRoute;
import com.jh.paymentchannel.pojo.WeixinResult;
import com.jh.paymentchannel.util.PaymentChannelConstants;
import com.jh.paymentchannel.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

@Controller
public class TopupService {

	private static final Logger log = LoggerFactory.getLogger(TopupService.class);

	@Autowired
	private TopupPayChannelBusiness topupPayChannelBusiness;

	@Autowired
	private PaymentChannelFactory factory;

	@Autowired
	private Util util;

	/** 发起请求 请求url, 并返回跳装的url */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/topup/request")
	public @ResponseBody Object topupRequest(HttpServletRequest request, @RequestParam(value = "amount") String amount,
											 @RequestParam(value = "ordercode") String ordercode, @RequestParam(value = "orderdesc") String orderdesc,
											 @RequestParam(value = "extra", required = false, defaultValue = "") String authcode,
											 @RequestParam(value = "userid", required = false, defaultValue = "") String userid,
											 @RequestParam(value = "brandcode", required = false, defaultValue = "0") String brandcode,
											 @RequestParam(value = "channel_type", required = false, defaultValue = "0") String channelType,
											 @RequestParam(value = "channel_tag", required = false, defaultValue = "YILIAN") String channelTag

	) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (!Tools.checkAmount(amount)) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_AMOUNT_ERROR);
			map.put(CommonConstants.RESP_MESSAGE, "支付金额有错");
			return map;
		}

		log.info("brandcode====="+brandcode);
		log.info("channelType====="+channelType);
		log.info("channelTag====="+channelTag);

		TopupPayChannelRoute payChannelRoute;
		String channelParams;
		String notifyURL;
		String returnURL;
		TopupRequest paymentRequest;
		try {
			payChannelRoute = topupPayChannelBusiness.getTopupChannelByBrandcode(brandcode,
					channelType, channelTag);

			log.info("payChannelRoute==========="+payChannelRoute);
			/*
			 * URI uri = util.getServiceUrl("user", "error url request!"); String
			 * url = uri.toString() + "/v1.0/user/channel/query";
			 *//** 根据的渠道标识或去渠道的相关信息 *//*
			 * MultiValueMap<String, String>
			 * requestEntity = new
			 * LinkedMultiValueMap<String, String>();
			 * requestEntity.add("channel_tag",
			 * payChannelRoute.getTargetChannelTag());
			 * RestTemplate restTemplate=new
			 * RestTemplate(); String resultObjx =
			 * restTemplate.postForObject(url,
			 * requestEntity, String.class);
			 * //LOG.info("RESULT================"+
			 * result); JSONObject jsonObject =
			 * JSONObject.fromObject(resultObjx);
			 * JSONObject resultObj =
			 * jsonObject.getJSONObject("result");
			 */
			log.info("payChannelRoute.getTargetChannelTag()===="+payChannelRoute.getTargetChannelTag());

			ChannelDetail channelDetail = topupPayChannelBusiness
					.getChannelDetailByTag(payChannelRoute.getTargetChannelTag());

			/** 更新订单的是否自动清算 */
			RestTemplate restTemplate = new RestTemplate();

			URI uri = util.getServiceUrl("transactionclear", "error url request!");
			String url = uri.toString() + "/v1.0/transactionclear/payment/update/autoclearing";

			/** 根据的用户手机号码查询用户的基本信息 */
			MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("auto_clearing", channelDetail.getAutoclearing());
			requestEntity.add("order_code", ordercode);
			restTemplate.postForObject(url, requestEntity, String.class);

			channelParams = channelDetail.getChannelParams();
			notifyURL = channelDetail.getNotifyURL();
			returnURL = channelDetail.getReturnURL();

			paymentRequest = factory.getTopupChannelRequest(payChannelRoute.getTargetChannelTag());
		} catch (RestClientException e1) {
			e1.printStackTrace();
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "亲.网络出错了哦,臣妾已经尽力了,请重试~");
			return map;
		}
		Map<String, String> result = new HashMap<String, String>();
		try {
			if (payChannelRoute.getTargetChannelTag().equals("QUICK_PAY")) {
				result = paymentRequest.topupRequest(request, amount, ordercode, orderdesc, userid, notifyURL,
						returnURL, channelParams);
			} else {
				result = paymentRequest.topupRequest(request, amount, ordercode, orderdesc, authcode, notifyURL,
						returnURL, channelParams);
			}

			log.info("result===="+result);
		} catch (Exception e) {
			log.error("==========请求通道异常===========" , e);
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "亲.网络出错了哦,臣妾已经尽力了,请重试~");
			return map;
		}
		log.info("result===="+result);
		if(result.get(CommonConstants.RESP_CODE) == null){
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "亲.由于位置原因,充值失败了哦,请重试~");
			return map;
		}
		if (result.get(CommonConstants.RESP_CODE).equalsIgnoreCase("success")
				|| "000000".equals(result.get(CommonConstants.RESP_CODE))) {
			if (result.get("channel_type").equalsIgnoreCase("quick")) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "成功");
				map.put(CommonConstants.RESULT, result.get("redirect_url"));
				return map;

			}
			//支付宝APP支付
			else if (result.get("channel_type").equalsIgnoreCase( PaymentChannelConstants.CHANNEL_ALIPAY_APP_PAY)) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "成功");
				map.put(CommonConstants.RESULT, result.get("body"));
				return map;

			} else if (result.get("channel_type").equalsIgnoreCase("sdj")) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "成功");
				//map.put(CommonConstants.RESULT, result.get("redirect_url"));
				return map;

			} else if (result.get("channel_type").equalsIgnoreCase("jf")) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, result.get("resp_message"));
				map.put(CommonConstants.RESULT, result.get("redirect_url"));
				return map;

			} else if (result.get("channel_type").equalsIgnoreCase("jfcoin")) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "成功");
				map.put(CommonConstants.RESULT, result.get("redirect_url"));
				return map;

			}else if (result.get("channel_type").equalsIgnoreCase("jfapi")) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "成功");
				map.put(CommonConstants.RESULT, result.get("redirect_url"));
				return map;

			}else if (result.get("channel_type").equalsIgnoreCase("yh")) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "成功");
				map.put(CommonConstants.RESULT, result.get("redirect_url"));
				return map;

			}else if (result.get("channel_type").equalsIgnoreCase("elong")) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "成功");
				map.put(CommonConstants.RESULT, result.get("result"));
				return map;

			} else if (result.get("channel_type").equalsIgnoreCase("weixin")) {

				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "成功");
				WeixinResult weixinResult = new WeixinResult();
				log.info(result.get("code_url"));
				weixinResult.setCodeUrl(result.get("code_url"));
				weixinResult.setImgUrl(result.get("img_url"));
				map.put(CommonConstants.RESULT, weixinResult);
				return map;

			} else if (result.get("channel_type").equalsIgnoreCase("alipay")) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "成功");
				WeixinResult weixinResult = new WeixinResult();
				log.info(result.get("code_url"));
				weixinResult.setCodeUrl(result.get("code_url"));
				weixinResult.setImgUrl(result.get("img_url"));

				map.put(CommonConstants.RESULT, weixinResult);
				return map;
			} else if (result.get("channel_type").equalsIgnoreCase("kuaijie")) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "成功");
				map.put(CommonConstants.RESULT, result.get("redirect_url"));
				return map;
			} else if (result.get("channel_type").equalsIgnoreCase("wftb2c")) {
				log.info("==================页面跳转==================");
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "成功");
				map.put(CommonConstants.RESULT, result.get("url"));
				return map;
			} else if (result.get("channel_type").equalsIgnoreCase("yb")) {
				log.info("==================页面跳转==================");
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESP_MESSAGE, "成功");
				map.put(CommonConstants.RESULT, result.get("redirect_url"));
				return map;
			} else if (result.get("channel_type").equalsIgnoreCase("quickpay")) {
				if (result.get("resp_code").equalsIgnoreCase("success")) {
					map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
					map.put(CommonConstants.RESP_MESSAGE, "成功");
					map.put(CommonConstants.RESULT, result.get("redirect_url"));
					return map;
				} else {
					map.put(CommonConstants.RESP_MESSAGE, "失败");
					map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					return map;
				}
			} else if (result.get("channel_type").equalsIgnoreCase("sf_pay")) {
				if (result.get("resp_code").equalsIgnoreCase("success")) {
					map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
					map.put(CommonConstants.RESP_MESSAGE, "成功");
					map.put(CommonConstants.RESULT, result.get("url"));
					return map;
				} else {
					map.put(CommonConstants.RESP_MESSAGE, "失败");
					map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					return map;
				}
			} else if (result.get("channel_type").equalsIgnoreCase("hl_pay")) {
				if ("nourl".equals(result.get("type"))) {
					log.info("====================" + "hl_pay:success" + "======================");
					map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
					map.put(CommonConstants.RESP_MESSAGE, "成功");
					log.info("==============map==============" + map.toString());
					return map;
				}
				else if (result.get("channel_type").equalsIgnoreCase("huizhi")){
					log.info("进入惠志====================================");
					map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
					map.put(CommonConstants.RESP_MESSAGE, "成功");
					map.put(CommonConstants.RESULT, result.get("redirect_url"));
					return map;
				}
				map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
				map.put(CommonConstants.RESULT, result.get("url"));
				map.put(CommonConstants.RESP_MESSAGE, "成功");
				return map;
			}

			map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
			map.put(CommonConstants.RESP_MESSAGE, "成功");
			map.put(CommonConstants.RESULT, result.get("redirect_url"));
			return map;


			// 失败
		} else {

			RestTemplate restTemplate = new RestTemplate();
			URI uri = util.getServiceUrl("transactionclear", "error url request!");
			String url = uri.toString() + "/v1.0/transactionclear/payment/update/remark";
			MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("ordercode",  ordercode+ "");

			String message = "";
			if (result.get("channel_type") == null || result.get("redirect_url") == null) {
				log.error("失败原因==========" + result);
				message = result.get(CommonConstants.RESP_MESSAGE);
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE,
						"".equals(message) || null == message ? "亲.由于未知原因支付失败了哦,请稍后重试~" : message);
				requestEntity.add("remark", "".equals(message) || null == message ? "亲.由于未知原因支付失败了哦,请稍后重试~" : message + "");
				restTemplate.postForObject(url, requestEntity, String.class);

				return map;
			}

			if (result.get("channel_type").equalsIgnoreCase("sdj")) {
				map.put(CommonConstants.RESP_CODE, result.get("resp_code"));
				map.put(CommonConstants.RESP_MESSAGE, result.get("resp_message"));

				requestEntity.add("remark", result.get("resp_message") + "");
				restTemplate.postForObject(url, requestEntity, String.class);

				return map;
			}
			if (result.get("channel_type").equalsIgnoreCase("jf")) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, result.get("resp_message"));
				map.put(CommonConstants.RESULT, result.get("redirect_url"));

				requestEntity.add("remark", result.get("resp_message") + "");
				restTemplate.postForObject(url, requestEntity, String.class);
				return map;
			}
			if (result.get("channel_type").equalsIgnoreCase("jfcoin")) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, result.get("resp_message"));
				map.put(CommonConstants.RESULT, result.get("redirect_url"));

				requestEntity.add("remark", result.get("resp_message") + "");
				restTemplate.postForObject(url, requestEntity, String.class);
				return map;
			}
			if (result.get("channel_type").equalsIgnoreCase("jfapi")) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, result.get("resp_message"));
				map.put(CommonConstants.RESULT, result.get("redirect_url"));

				requestEntity.add("remark", result.get("resp_message") + "");
				restTemplate.postForObject(url, requestEntity, String.class);
				return map;
			}
			if (result.get("channel_type").equalsIgnoreCase("yh")) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, result.get("resp_message"));
				map.put(CommonConstants.RESULT, result.get("redirect_url"));

				requestEntity.add("remark", result.get("resp_message") + "");
				restTemplate.postForObject(url, requestEntity, String.class);
				return map;
			}
			if (result.get("channel_type").equalsIgnoreCase("elong")) {
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
				map.put(CommonConstants.RESP_MESSAGE, result.get("resp_message"));
				// map.put(CommonConstants.RESULT, result.get("redirect_url"));
				requestEntity.add("remark", result.get("resp_message") + "");
				restTemplate.postForObject(url, requestEntity, String.class);
				return map;
			}
			if (result.get("channel_type").equalsIgnoreCase("yb")) {
				map.put(CommonConstants.RESP_MESSAGE, result.get("resp_message"));
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);

				requestEntity.add("remark", result.get("resp_message") + "");
				restTemplate.postForObject(url, requestEntity, String.class);
				return map;
			}
			if (result.get("channel_type").equalsIgnoreCase("sf_pay")) {
				map.put(CommonConstants.RESP_MESSAGE, result.get("message"));
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);

				requestEntity.add("remark", result.get("resp_message") + "");
				restTemplate.postForObject(url, requestEntity, String.class);
				return map;
			}
			if (result.get("channel_type").equalsIgnoreCase("hl_pay")) {
				map.put(CommonConstants.RESP_MESSAGE, result.get("message"));
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);

				requestEntity.add("remark", result.get("resp_message") + "");
				restTemplate.postForObject(url, requestEntity, String.class);
				return map;
			}if(result.get("channel_type").equalsIgnoreCase("huizhi")){
				map.put(CommonConstants.RESP_MESSAGE, result.get("message"));
				map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);

				requestEntity.add("remark", result.get("resp_message") + "");
				restTemplate.postForObject(url, requestEntity, String.class);
				return map;

			}
			if (result.get("channel_type").equalsIgnoreCase("wftb2c")) {
				if (result.get("resp_code").equalsIgnoreCase("paying")) {
					log.info("==================等待对方支付中==================");
					map.put(CommonConstants.RESP_MESSAGE, "等待对方支付中");
					map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);

					requestEntity.add("remark", "等待对方支付中 "+ "");
					restTemplate.postForObject(url, requestEntity, String.class);

					return map;
				} else {
					map.put(CommonConstants.RESP_MESSAGE, "收款失败");
					map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
					map.put(CommonConstants.RESULT, result.get("url"));

					requestEntity.add("remark", "收款失败 "+ "");
					restTemplate.postForObject(url, requestEntity, String.class);
					return map;
				}
			}
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);

			if (result.get(CommonConstants.RESP_MESSAGE) != null
					&& !result.get(CommonConstants.RESP_MESSAGE).equalsIgnoreCase("")) {
				map.put(CommonConstants.RESP_MESSAGE, result.get(CommonConstants.RESP_MESSAGE));
				requestEntity.add("remark", result.get(CommonConstants.RESP_MESSAGE)+ "");
				restTemplate.postForObject(url, requestEntity, String.class);
			} else {
				map.put(CommonConstants.RESP_MESSAGE, "失败");

				requestEntity.add("remark", "失败" + "");
				restTemplate.postForObject(url, requestEntity, String.class);
			}

			/*
			 * else if(result.get("channel_type").equalsIgnoreCase(
			 * "kuaijie_sdj_bindcardsuccess")){
			 * map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			 * map.put(CommonConstants.RESP_MESSAGE, "失败"); return map; }
			 */

			/*
			 * else
			 * if(result.get("channel_type").equalsIgnoreCase("jf_payerror")){
			 * map.put(CommonConstants.RESP_CODE,CommonConstants.SUCCESS);
			 * map.put(CommonConstants.RESP_MESSAGE, "失败");
			 * map.put(CommonConstants.RESULT, result.get("redirect_url"));
			 * return map; }
			 */

			/*
			 * map.put(CommonConstants.RESP_CODE,CommonConstants.FALIED);
			 * map.put(CommonConstants.RESP_MESSAGE, "失败");
			 * map.put(CommonConstants.RESULT, result.get("redirect_url"));
			 * return map;
			 */

		}
		return null;

	}

}
